﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompresson
{
    internal class Program
    {
        static void SaveCompressedFile(string filename,string data)
        {
            FileStream fileStream=new FileStream(filename,FileMode.Create,FileAccess.Write);
            GZipStream comStream=new GZipStream(fileStream, CompressionMode.Compress);
            StreamWriter writer=new StreamWriter(comStream);
            writer.Write(data);
            writer.Close();
            comStream.Close();
            fileStream.Close();
        }

        static string LoadCompressedFile(string filename)
        {
            FileStream fs=new FileStream(filename,FileMode.Open,FileAccess.Read);
            GZipStream gs=new GZipStream(fs, CompressionMode.Decompress);
            StreamReader rs=new StreamReader(gs);
            string data = rs.ReadToEnd();
            rs.Close();
            gs.Close();
            fs.Close();
            return data;
        }
        static void Main(string[] args)
        {
            try
            {
                string filename = "comFile.txt";
                Console.WriteLine("输入要压缩的数据：");
                string scs=Console.ReadLine();
                StringBuilder ssm=new StringBuilder(scs.Length*100);
                for (int i = 0; i < 100; i++)
                {
                    ssm.Append(scs);
                }

                scs=ssm.ToString();
                Console.WriteLine($"原数据大小:{scs.Length}bytes.");
                SaveCompressedFile(filename,scs);
                Console.WriteLine($"数据压缩完成.文件名：{filename}");
                FileInfo file = new FileInfo(filename);
                Console.WriteLine($"压缩后文件大小:{file.Length}");

                string rcs= LoadCompressedFile(filename);
                rcs=rcs.Substring(0,rcs.Length/100);
                Console.WriteLine($"恢复数据:{rcs}");


                Console.ReadLine();



            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                return;
            }
        }
    }
}
